package com.leyou.zuul.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class GlobalCorsConfig {
    @Bean
    public CorsFilter crosFilter() {
        //1.添加CORS配置信息，先创建配置对象
        CorsConfiguration config = new CorsConfiguration();
        //1.1  允许的域，不能写* 要写具体的域名，否则无法使用cookie
        config.addAllowedOrigin("http://manage.leyou.com");
        config.addAllowedOrigin("http://www.leyou.com");
        //1.2  是否发送cookie信息
        config.setAllowCredentials(true);
        //1.3  允许的请求方式
        config.addAllowedMethod("OPTIONS");
        config.addAllowedMethod("HEAD");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("PUT");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PATCH");
        //1.4  允许的头
        config.addAllowedHeader("*");

        //2.  添加映射路径，拦截一切请求
        UrlBasedCorsConfigurationSource configurationSource = new UrlBasedCorsConfigurationSource();
        configurationSource.registerCorsConfiguration("/**",config);

        //3.  返回新的CorsFilter
        return new CorsFilter(configurationSource);
    }
}
